#include "board.h"

//定义控制块
static rt_thread_t RF_thread = RT_NULL;
static rt_thread_t MODBUS_thread = RT_NULL;
static rt_thread_t period_thread = RT_NULL;
static rt_thread_t Connect_thread = RT_NULL;

//函数声明
static void RF_thread_entry( void* parameter );
static void Modbus_thread_entry( void* parameter );
static void period_thread_entry( void* parameter );
static void Connect_thread_entry( void* parameter );

_Main_t mainPar;
_Sys_t  Sys;
/*
串口2为WIFI接口
串口3为RFID接口
串口1为485接口
*/
void IwdgReload(void)
{
	GPIO_SetBits(GPIOB, GPIO_Pin_9);
	IWDG_ReloadCounter();
	GPIO_ResetBits(GPIOB, GPIO_Pin_9);
}
//处理每秒计算任务
static void period_thread_entry( void* parameter )
{
	int time =  0;
	
	
	mainPar.deviceAdd = 0x01;//RTU的读取地址始终为1
	
	
    while ( 1 )
    {
			
		time ++;
		if(time >= 50)
		{
			time = 0;
			mainPar.tickSec++;
			LED1_TOGGLE;
			LED2_TOGGLE;
			if(mainPar.tickSec%1 == 0){rt_kprintf("run time:%dH-%dM-%dS.\r\n",((mainPar.tickSec/60)/60),((mainPar.tickSec/60)%60),mainPar.tickSec%60);	 }	
		}
		IwdgReload();
		rt_thread_delay( 20 ); //时间片时间设置
		
		//控制单次运行时间
		if(mainPar.commTime != 0) {
			mainPar.commTime -- ;
		}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		if(mainPar.Yled >= 2)//绿色
		{
			
			mainPar.Nled = 0;
			mainPar.Yled = 0; 
			GPIO_ResetBits(GPIOB, GPIO_Pin_12);
			GPIO_SetBits(GPIOB, GPIO_Pin_13);
			GPIO_ResetBits(GPIOB, GPIO_Pin_14);
//			rt_thread_delay( 500 );
		}
		else  if(mainPar.Nled >= 3)//黄色
		{
			mainPar.Nled = 0;
			mainPar.Yled = 0;
//			rt_kprintf("No label.\r\n");
			GPIO_ResetBits(GPIOB, GPIO_Pin_12);
			GPIO_ResetBits(GPIOB, GPIO_Pin_13);
			GPIO_SetBits(GPIOB, GPIO_Pin_14);
		}
		
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	



   }
}
//处理与modbus协议之间的回复数据
static void Modbus_thread_entry( void* parameter )
{
    while ( 1 )
    {

		rt_thread_delay( 20 ); 
		MODS_Poll();
		IwdgReload();
		
    }
}
//处理模块的运行相关事宜
//处理模块的回复消息，读卡等事物
static void RF_thread_entry( void* parameter )
{
	SIM7500Init();	
    while ( 1 )
    {

		rt_thread_delay( 5 );
		SIM7500_DataCheck();
		IwdgReload();
		
    }
}
//处理与上位机通讯部分的协议
//负责对寄存器进行更新等
static void Connect_thread_entry( void* parameter )
{
	#define READ_TIME_NUM  			100//周期设置，设置时间片的个数,每一个时间片为20ms
	#define REPETITION_NUM			3//新标签连续重复的次数
	#define CLEAR_CARD_NUM			10//指定次数无卡读取时，清空寄存器，判断为无卡状态
	
		int i = 0;
		int maxNum = 0;
		int timeOut = 0;
		int led_out = 0;
		int repetitionNum = 0;//当前新标签的连续读取次数
		int readCradNum	= 0;//记录单个周期内的读卡次数
		int RfPa = 0;				//记录模块功率 
		
	
		mainPar.RfPaupdeta  = 0;
		rt_thread_delay( 100 );
		SIM7500_COMM_Start();
		rt_thread_delay( 100 );	
		SIM7500_COMM_getPower();
		rt_thread_delay( 100 );
    while ( 1 )
    {
		rt_thread_delay( 100 );
		
//		if(mainPar.RfPaupdeta == 1)
//		{
			SIM7500_COMM_setPower(reafMdodbusReg(MReg_Power));
			rt_kprintf("set power.power:%ddBm.\r\n",reafMdodbusReg(MReg_Power));
//			mainPar.RfPaupdeta = 0;//标记为已更新
//		}
			IwdgReload();
			rt_kprintf("********************************************\r\n");
			mainPar.inCardnum = 0;
			rt_kprintf("start read card once.\r\n");
			mainPar.commTime = READ_TIME_NUM;
			//循环发生多个时间片的单次读卡
			readCradNum = 0;
			while(mainPar.commTime)
			{
				//发送单次读卡命令
				SIM7500_COMM_ReadOnceTag();
				readCradNum ++;
				mainPar.breakCommState = 0;
				timeOut = 100;//单位为10ms，即1s内无回复报错退出
				//超时检测
				while((mainPar.breakCommState == 0)&&(timeOut))
				{
					timeOut --;
					rt_thread_delay( 10 );
					IwdgReload();
				}
			//接收函数自动收集读卡数据
			}
			rt_kprintf("Total reads count:%d\r\n",readCradNum);
			
			if(mainPar.inCardnum != 0)
			{
				//判断读卡次数最多的卡
				rt_kprintf("Total max card count:%d\r\n",mainPar.inCardnum);
				
				i = 0;
				maxNum = 0;

				while(i < mainPar.inCardnum)
					{
						rt_kprintf("<%d>,reads num:%d \r\n crad code:",i+1,mainPar.NewEPC[i][1]);	
						printf_x(&mainPar.NewEPC[i][2],mainPar.NewEPC[i][0]);						
						if(mainPar.NewEPC[i][1] >= maxNum)
							{
								mainPar.max = i;
								maxNum = mainPar.NewEPC[i][1];
							}
						i++;
					}
//				rt_kprintf("The maximum number of reads is number <%d> card, number of reads:%d \r\n card num:",i,mainPar.NewEPC[mainPar.max][1]);	
					rt_kprintf("max card is <%d>,read num<%d> \r\n card code:",i,mainPar.NewEPC[mainPar.max][1]);	
				printf_x(&mainPar.NewEPC[mainPar.max][2],mainPar.NewEPC[mainPar.max][0]);
					
				//是否存在新的标签进入
				if(DataComp(&mainPar.NewEPC[mainPar.max][2],&mainPar.oldEPC[0][2],mainPar.NewEPC[mainPar.max][0]) == TRUE)
				{
					//存在不相同的标签
					repetitionNum  = 0;

//					mainPar.readState = 0x00;//标记为无卡
					rt_kprintf("new card.\r\n");
					rt_memset(&mainPar.oldEPC[0][0],0x00,EPC_BYTE_NUM);
					rt_memcpy(&mainPar.oldEPC[0][0],&mainPar.NewEPC[mainPar.max][0],EPC_BYTE_NUM);
					
				}
				//标签跟上次一样
				else 
				{
					repetitionNum ++;//记录重复次数
					rt_kprintf("repetition<%d>,card code:",repetitionNum);
					printf_x(&mainPar.oldEPC[0][2],mainPar.oldEPC[0][0]);
//					rt_kprintf("repetitionNum = 0.r\n");
					//如果相同次数超过定义，就更新到输出数组中
					if(repetitionNum >=  REPETITION_NUM)
					{
						if(repetitionNum > 1000)repetitionNum = 1000;//限定参数，防止越界
						rt_memset(&mainPar.outEPC[0][0],0x00,EPC_BYTE_NUM);
						rt_memcpy(&mainPar.outEPC[0][0],&mainPar.oldEPC[0][0],EPC_BYTE_NUM);
						mainPar.readState = CLEAR_CARD_NUM ;//标记读到卡
						rt_kprintf("filtration ok:");	
					}
					if(mainPar.readState != 0)
					{
						rt_kprintf("out card code:");	
						printf_x(&mainPar.outEPC[0][2],mainPar.outEPC[0][0]);
					}
				}
				//设置LED为绿色状态
			led_out = 0;			
			}
			else {
					if(mainPar.readState >0)
					{
						rt_kprintf("cache card,residue:%d\r\n",mainPar.readState);
						printf_x(&mainPar.outEPC[0][2],mainPar.outEPC[0][0]);
						mainPar.readState --;//标记为无卡
					}
					rt_kprintf("not card.\r\n");
					rt_memset(&mainPar.oldEPC[0][0],0x00,EPC_BYTE_NUM);
				}
			rt_kprintf("end reads.\r\n");
				
			if(mainPar.readState != 0)
			{
				writeMdodbusReg(MReg_CardNum,mainPar.inCardnum);
				writeMdodbusReg(MReg_CardMaxCount,mainPar.outEPC[0][1]);
				writeMdodbusReg(MReg_CardMax1,(mainPar.outEPC[0][2]<<8)|(mainPar.outEPC[0][3]));//拷贝EPC到modbus寄存器中，以供读取
				writeMdodbusReg(MReg_CardMax2,(mainPar.outEPC[0][4]<<8)|(mainPar.outEPC[0][5]));//拷贝EPC到modbus寄存器中，以供读取
				writeMdodbusReg(MReg_CardMax3,(mainPar.outEPC[0][6]<<8)|(mainPar.outEPC[0][7]));//拷贝EPC到modbus寄存器中，以供读取
				writeMdodbusReg(MReg_CardMax4,(mainPar.outEPC[0][8]<<8)|(mainPar.outEPC[0][9]));//拷贝EPC到modbus寄存器中，以供读取
				writeMdodbusReg(MReg_CardMax5,(mainPar.outEPC[0][10]<<8)|(mainPar.outEPC[0][11]));//拷贝EPC到modbus寄存器中，以供读取
				writeMdodbusReg(MReg_CardMax6,(mainPar.outEPC[0][12]<<8)|(mainPar.outEPC[0][13]));//拷贝EPC到modbus寄存器中，以供读取
				writeMdodbusReg(MReg_CardMax7,(mainPar.outEPC[0][14]<<8)|(mainPar.outEPC[0][15]));//拷贝EPC到modbus寄存器中，以供读取
				writeMdodbusReg(MReg_CardMax8,(mainPar.outEPC[0][16]<<8)|(mainPar.outEPC[0][17]));//拷贝EPC到modbus寄存器中，以供读取
				writeMdodbusReg(MReg_CardMax9,(mainPar.outEPC[0][18]<<8)|(mainPar.outEPC[0][19]));//拷贝EPC到modbus寄存器中，以供读取		
			}
			else 
			{
				writeMdodbusReg(MReg_CardNum,0x0000);
				writeMdodbusReg(MReg_CardMaxCount,0x0000);
				writeMdodbusReg(MReg_CardMax1,0x0000);//拷贝EPC到modbus寄存器中，以供读取
				writeMdodbusReg(MReg_CardMax2,0x0000);//拷贝EPC到modbus寄存器中，以供读取
				writeMdodbusReg(MReg_CardMax3,0x0000);//拷贝EPC到modbus寄存器中，以供读取
				writeMdodbusReg(MReg_CardMax4,0x0000);//拷贝EPC到modbus寄存器中，以供读取
				writeMdodbusReg(MReg_CardMax5,0x0000);//拷贝EPC到modbus寄存器中，以供读取
				writeMdodbusReg(MReg_CardMax6,0x0000);//拷贝EPC到modbus寄存器中，以供读取
				writeMdodbusReg(MReg_CardMax7,0x0000);//拷贝EPC到modbus寄存器中，以供读取
				writeMdodbusReg(MReg_CardMax8,0x0000);//拷贝EPC到modbus寄存器中，以供读取
				writeMdodbusReg(MReg_CardMax9,0x0000);//拷贝EPC到modbus寄存器中，以供读取	
			}	

	}
}
int main( void )
{

	RF_thread =                        
        rt_thread_create( "RF",         
                          RF_thread_entry,  
                          RT_NULL,           
                          512,                 
                          3,                   
                          20 );    
	MODBUS_thread =                        
        rt_thread_create( "MODBUS",         
                          Modbus_thread_entry,  
                          RT_NULL,           
                          1024,                 
                          6,                   
                          20 ); 
    period_thread =                        
        rt_thread_create( "period",             
                          period_thread_entry,  
                          RT_NULL,           
                          512,                 
                          4,                   
                          20 );  	
    Connect_thread =                        
        rt_thread_create( "Connect",             
                          Connect_thread_entry,  
                          RT_NULL,           
                          4096,                 
                          5,                   
                          20 ); 
						  
	IWDG_Feed_Init( IWDG_Prescaler_32, 4000 );
	
    if ( RF_thread != RT_NULL )
        rt_thread_startup( RF_thread );
	if ( MODBUS_thread != RT_NULL )
        rt_thread_startup( MODBUS_thread );
    if ( period_thread != RT_NULL )
        rt_thread_startup( period_thread );
    if(Connect_thread != RT_NULL)
         rt_thread_startup( Connect_thread );
	return -1;

}


